<?php

namespace app\api\model;
use app\service\UserLevel;

class YaoqingRecords extends Common
{
    static public function index($user_id, $to_user, $money, $remark, $type = 0, $order_id = '', $data = 0, $update = 0, $show_money = 0, $source_uid = 0)
    {
        $User = new User;
        $Self = new YaoqingRecords;

        $money = changefloor($money);
        $show_money = $show_money <> 0 ? $show_money : $money;

        $balance = $User->master()->where(['id' => $user_id])->value('score');
        $current_balance = $data ? ($balance - $money) : ($balance + $money);
        $state = false;
        if ($update) {
            $income = $Self->master()->where(['uid' => $user_id, 'order_id' => $order_id])->find();

            if ($income) {
                self::update([
                    'id' => $income['id'],
                    'money' => $income['money'] + $money,
                    'show_money' => ($income['show_money'] ?? 0) + $show_money,
                    'balance' => $current_balance,
                    'time' => time(),
                ]);
            } else {
                $Self->create([
                    'uid' => $user_id,
                    'touid' => $to_user,
                    'content' => $remark,
                    'money' => $money,
                    'show_money' => $show_money,
                    'type' => $type,
                    'data' => $data,
                    'order_id' => $order_id,
                    'balance' => $current_balance,
                    'source_uid'=>$source_uid,
                    'time' => time()
                ]);
            }
        } else {
            if ($money > 0 && $current_balance >= 0) {
                $Self->create([
                    'uid' => $user_id,
                    'touid' => $to_user,
                    'content' => $remark,
                    'money' => $money,
                    'show_money' => $show_money,
                    'type' => $type,
                    'data' => $data,
                    'order_id' => $order_id,
                    'balance' => $current_balance,
                    'source_uid'=>$source_uid,
                    'time' => time()
                ]);
            }
        }

        if ($money > 0 && $current_balance >= 0) {
            if ($data) {
                $User->where(['id' => $user_id])->setDec('score', $money);
            } else {
                $User->where(['id' => $user_id])->setInc('shouyi', $money);

                $User->where(['id' => $user_id])->setInc('score', $money);

                if (stripos($remark, '收益') && stripos($remark, '充值') === false) {
                    // 用户业绩统计
                    UserData::createData($user_id, $money, 'income');
                }
            }
            $state = true;
            UserLevel::checkUserLevel($user_id);
        }
        return $state;
    }
}
